package io.github.kimmking;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.lang.System;

public class Main {

    public static void main(String[] args) {

        if(args.length<1) {
            System.out.println("java -jar FileConvert.jar file-path");
            System.out.println("java -jar FileConvert.jar directory-path");
            return;
        }

        File f = new File(args[0]);
        if(f.isDirectory()){
            File[] fs = f.listFiles();
            int count = 0;
            for (File file : fs){
                if(file.isFile()){
                    convertFile(file);
                    count ++;
                }
            }
            System.out.println("convert files("+ count + ")!");
        }else{
            convertFile(f);
        }
    }

    public static void convertFile(File file){
        File file1 = file;
        File file2 = null;
        if(file.getName().endsWith(".fck"))
            file2 = new File(file1.getAbsolutePath().substring(0,file1.getAbsolutePath().length()-4));
        else
            file2 = new File(file1.getAbsolutePath()+".fck");

        System.out.println("file1=> "+ file1.getAbsolutePath());
        System.out.println("file2=> "+ file2.getAbsolutePath());
        System.out.println("-------------------------------");

        byte[] byData = new byte[4096];

        try
        {
            FileInputStream fs1 = new FileInputStream(file1);
            FileOutputStream fs2 = new FileOutputStream(file2);

            long size = file1.length();
            if (size == 0)
                return;

            int count = fs1.read(byData, 0, byData.length);
            long total = 0;
            while (count > 0)
            {
                convert(byData, count);
                fs2.write(byData, 0, count);

                total += count;
                double d1 = Math.floor((total * 100.0 / size));
                double d2 = Math.floor((total - count) * 100.0 / size);
                if (d1 > d2)
                {
                    fs2.flush();
                    System.out.println("convert file("+ file1.getName() + "):" + (int)d1 + "%");
                }
                count = fs1.read(byData, 0, byData.length);
            }
            System.out.println("convert file(" + file1.getName() + "):" + 100 + "%");

            fs1.close();
            fs2.close();
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
    }

    private static void convert(byte[] bs, int len)
    {
        for (int i = 0; i < len; i++)
        {
            bs[i] = (byte)~bs[i];
        }
    }
}
